
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodlist: [],
    i: 1
  },
  mutations: {
    // 请求到的数据
    goodlist(state, data) {
      state.goodlist = data
    },
    // 删除
    del(state, id) {
      let a = state.goodlist.filter(item => {
        return item._id != id
      })
      state.goodlist = a
    },
    // 增加数量
    jia(state, num) {
      state.goodlist.filter(item => {
        if (item._id == num) {
          item.num++
        }
      })
    },
    // 数量减少
    jian(state, num) {
      state.goodlist.filter(item => {
        if (item._id == num) {

          item.num--
          if (item.num < 1) {
            alert("不能再减少了")
            item.num = 1
          }
        }
      })
    },
    // 全选
    all(state, checked) {
      state.i++
      if (state.i % 2 == 0) {
        checked = true
      } else {
        checked = false
      }
      console.log(checked)
      state.goodlist.forEach(item => {
        item.checked = checked
      })
    },
    // 全不选
    noall(state, checked) {
      state.goodlist.forEach(item => {
        item.checked = checked
      })
    },
    // 多选删除
    duodel(state) {
      let a = state.goodlist.filter(item => {
        return item.checked == false
      })
      state.goodlist = a
    },
    // 区间搜索
    sou(state, arr) {
      let a = state.goodlist.filter(item => {
        if (item.price >= Number(arr[0]) && item.price <= Number(arr[1])) {
          return item
        }
      })
      state.goodlist = a
    },
    // 从小到大
    sort(state) {
      state.goodlist.sort((n1, n2) => {
        return n1.price - n2.price
      })
    }
  },
  getters: {
    // 计算总价
    sum(state) {
      let sum = 0
      state.goodlist.forEach(item => {
        if (item.checked == true) {
          sum += item.price * item.num
        }
      })
      return sum
    },
  },
  actions: {
  },
  modules: {
  }
})
